package com.ews.onlineexchange.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.Query;

import com.ews.onlineexchange.model.ProfessionRatingRecord;
import com.ews.onlineexchange.service.EntityHome;
import com.ews.onlineexchange.service.UserService;

@Named
@ConversationScoped
public class ProfessionRatingRecordHome extends EntityHome<ProfessionRatingRecord, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	ServiceSupplierHome supplierHome;
	private boolean hasRated = false;
	
	private static final String GET_RATING_BY_SUPPLIER = " " +
					"  SELECT professionRatingRecord  " +
					" FROM ProfessionRatingRecord professionRatingRecord"+
					" WHERE professionRatingRecord.supplier.id = :supplierId " +
					" AND  professionRatingRecord.year = :year ";
					
	
	@Override
	public ProfessionRatingRecord createInstance() {
		
		return super.createInstance();
	}
	
	@Override
	public void initConversation() {
		String supplierId = supplierHome.getInstance().getId();
		Query query = getEntityManager().createQuery(GET_RATING_BY_SUPPLIER);
		query.setParameter("supplierId", supplierId);
		query.setParameter("year", Calendar.getInstance().get(Calendar.YEAR));
		List<ProfessionRatingRecord>  records = query.getResultList();
		if(records.size() > 0) {
			ProfessionRatingRecord record = records.get(0);
			if( record.getYear() ==Calendar.getInstance().get(Calendar.YEAR)) {
				setId(record.getId());
				setHasRated(true);
				super.loadInstance();
			}
		}
		super.initConversation();
	}

	@Inject
	UserService userService;
	@Override
	public String saveAndFlush() {
		getInstance().setSupplier(supplierHome.getInstance());
		getInstance().setRatingDate(new Date());
		getInstance().setYear(Calendar.getInstance().get(Calendar.YEAR));
		getInstance().setRatingUser(userService.getLoginedUser());
//		getEntityManager().persist(arg0);(getInstance());
		return super.saveAndFlush();
	}

	public boolean isHasRated() {
		return hasRated;
	}

	public void setHasRated(boolean hasRated) {
		this.hasRated = hasRated;
	}
	
	
}
